package com.jsz.peini.controller.app;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jsz.peini.bean.coupon.CouponGet;
import com.jsz.peini.bean.coupon.CouponInfo;
import com.jsz.peini.bean.coupon.CouponRange;
import com.jsz.peini.bean.coupon.CouponRangeExample;
import com.jsz.peini.bean.coupon.CouponUser;
import com.jsz.peini.bean.seller.SellerDiscount;
import com.jsz.peini.bean.seller.SellerDiscountExample;
import com.jsz.peini.bean.seller.SellerDiscountExample.Criteria;
import com.jsz.peini.bean.seller.SellerInfo;
import com.jsz.peini.bean.user.UserInfo;
import com.jsz.peini.bean.user.UserSms;
import com.jsz.peini.bean.user.UserSmsExample;
import com.jsz.peini.common.constants.Constants;
import com.jsz.peini.common.util.AppPush;
import com.jsz.peini.common.util.DateTimeUtils;
import com.jsz.peini.common.util.EhcacheUtil;
import com.jsz.peini.common.util.PeiniUtils;
import com.jsz.peini.common.util.SmsSendUtil;
import com.jsz.peini.common.util.UploadQN;
import com.jsz.peini.mapper.coupon.CouponGetMapper;
import com.jsz.peini.mapper.coupon.CouponInfoMapper;
import com.jsz.peini.mapper.coupon.CouponRangeMapper;
import com.jsz.peini.mapper.seller.SellerDiscountMapper;
import com.jsz.peini.mapper.seller.SellerInfoMapper;
import com.jsz.peini.mapper.sign.SignInfoMapper;
import com.jsz.peini.mapper.user.UserInfoMapper;
import com.jsz.peini.mapper.user.UserSmsMapper;
import com.jsz.peini.redis.base.RedisConstants;
import com.jsz.peini.redis.base.RedisUtil;
import com.jsz.peini.redis.util.SignRedisUtil;
import com.jsz.peini.service.coupon.CouponInfoService;
import com.sun.org.apache.bcel.internal.generic.NEW;

@Controller
public class CouponInfoContorller {
	private static final Logger logger = LoggerFactory.getLogger(CouponInfoContorller.class);
	@Autowired
	private CouponInfoService couponInfoService;
	@Resource
	private UserInfoMapper userInfoMapper;
	@Resource
	private CouponInfoMapper couponInfoMapper;
	@Resource
	private CouponGetMapper couponGetMapper;
	@Resource
	private CouponRangeMapper couponRangeMapper;
	@Resource
	private SellerDiscountMapper sellerDiscountMapper;
	@Resource
	private SellerInfoMapper sellerInfoMapper;
	@Resource
	private UserSmsMapper userSmsMapper;
	@Resource
	private SignInfoMapper signInfoMapper;
	
	/**
	 * 买单选择优惠券列表接口
	 * @param request
	 * @param userId
	 * @param sellerInfoId
	 * @param totalMoney
	 * @param exclusiveMoney
	 * @param payType
	 * @return
	 */
	/*@RequestMapping(value="/getCouponInfoByPay")
	@ResponseBody
	public Object getCouponInfoByPay(HttpServletRequest request,
			@RequestParam(value="userId") String userId,
			@RequestParam(value="sellerInfoId") Integer sellerInfoId,
			@RequestParam(value="totalMoney") Double totalMoney,
			@RequestParam(value="exclusiveMoney",required=false,defaultValue="0") Double exclusiveMoney,
			@RequestParam(value="payType") Integer payType,//1金币；2微信；3支付宝
			@RequestParam(value="page",required=false,defaultValue="1") Integer page,
			@RequestParam(value="rows",required=false,defaultValue="10") Integer rows
			){
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		try{	
			JSONObject obj = PeiniUtils.validToken(userId);
			if(obj.getInteger("resultCode") != 1){
				return obj;
			}
			userId = obj.getString("userId");
			
			//查询店铺信息
			SellerInfo sellerInfo = sellerInfoMapper.selectByPrimaryKey(sellerInfoId);
			Integer provinceId = sellerInfo.getProvinceid();
			Integer cityId = sellerInfo.getCityCode();
			Integer sellerType = sellerInfo.getSellerType();
			Integer sellerLabel = Integer.parseInt(sellerInfo.getLabelsId());
			
			int goldNum = 0;
			int alipay = 0;
			int wxpay = 0;
			int week = DateTimeUtils.getWeek();
			SellerDiscountExample example = new SellerDiscountExample();
			Criteria criteria = example.createCriteria();
			criteria.andStartNumLessThanOrEqualTo(week);
			criteria.andEndNumGreaterThanOrEqualTo(week);
			criteria.andSellerInfoIdEqualTo(sellerInfoId);
			List<SellerDiscount> list = sellerDiscountMapper.selectByExample(example);
			for (SellerDiscount dis : list) {
				String frontStr = DateTimeUtils.formatDateTime2String(new Date(), "yyyy-MM-dd");
				String startTime = frontStr+" "+dis.getStartTime();
				String endTime = frontStr+" "+dis.getEndTime();
				
				Date now = new Date();
				if(DateTimeUtils.formatString2Date(startTime, "yyyy-MM-dd HH:mm").before(now) && DateTimeUtils.formatString2Date(endTime, "yyyy-MM-dd HH:mm").after(now)){
					goldNum = dis.getGoldNum();
					alipay = dis.getZfbNum();
					wxpay = dis.getWeixinNum();
				}
			}
			
			List<HashMap<String, Object>> validList = new ArrayList<HashMap<String, Object>>();
			
			//查询用户所有未过期可以使用的优惠券
			List<Integer> couponIds = new ArrayList<Integer>();
			HashMap<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("userId", userId);
			//paramMap.put("type", 1);
			List<HashMap<String, Object>> cList = couponInfoMapper.getCouponInfoByPay(paramMap);
			
			//去除满减后的数据
			List<HashMap<String, Object>> manjianList = new ArrayList<HashMap<String, Object>>();
			
			for (HashMap<String, Object> cMap : cList) {
				//优惠券使用规则
				String couponRule = cMap.get("couponRule").toString();
				
				//使用规则容器
				//List<HashMap<String, Object>> rulelist = new ArrayList<HashMap<String, Object>>();
				
				boolean flag = true;
				
				if(StringUtils.isNotBlank(couponRule)){
					String [] rules = couponRule.split(",");
					for (int i = 0; i < rules.length; i++) {
						if(StringUtils.isNotBlank(rules[i])){
							paramMap = new HashMap<String, Object>();
							
							String name = "";
							switch (rules[i]) {
								case "1":
									//name = "消费满"+cMap.get("ruleMoney").toString()+"元可抵现金使用";
									
									if(payType == 1){//金币支付
										if(goldNum == 0){//没有折扣
											if((totalMoney-exclusiveMoney)<Double.parseDouble(cMap.get("ruleMoney").toString())){
												couponIds.add(Integer.parseInt(cMap.get("couponId").toString()));
												//validList.add(cMap);
												flag = false;
											}
										}else{
											if((totalMoney-exclusiveMoney)*goldNum/100 < Double.parseDouble(cMap.get("ruleMoney").toString())){
												couponIds.add(Integer.parseInt(cMap.get("couponId").toString()));
												//validList.add(cMap);
												flag = false;
											}
										}
									}else if(payType == 2){//微信支付
										if(wxpay == 0){//没有折扣
											if((totalMoney-exclusiveMoney)<Double.parseDouble(cMap.get("ruleMoney").toString())){
												couponIds.add(Integer.parseInt(cMap.get("couponId").toString()));
												//validList.add(cMap);
												flag = false;
											}
										}else{
											if((totalMoney-exclusiveMoney)*wxpay/100 < Double.parseDouble(cMap.get("ruleMoney").toString())){
												couponIds.add(Integer.parseInt(cMap.get("couponId").toString()));
												//validList.add(cMap);
												flag = false;
											}
										}
									}else if(payType == 3){//支付宝支付
										if(alipay == 0){//没有折扣
											if((totalMoney-exclusiveMoney)<Double.parseDouble(cMap.get("ruleMoney").toString())){
												couponIds.add(Integer.parseInt(cMap.get("couponId").toString()));
												//validList.add(cMap);
												flag = false;
											}
										}else{
											if((totalMoney-exclusiveMoney)*alipay/100 < Double.parseDouble(cMap.get("ruleMoney").toString())){
												couponIds.add(Integer.parseInt(cMap.get("couponId").toString()));
												//validList.add(cMap);
												flag = false;
											}
										}
									}
									
									break;
								case "2":
									//name = "优惠范围不参与积分赠送";
									break;
								case "3":
									//name = "使用优惠券不参与积分赠送";
									break;
								case "4":
									//name = "优惠券与金币折扣不能同时存在";
									
									if(payType == 1){
										flag = false;
									}
									
									break;
								default:
									break;
							}
							//paramMap.put("name", name);
							//rulelist.add(paramMap);
						}
					}
				}
				
				//cMap.put("rulelist", rulelist);
				
				if(flag == true){
					//logger.info(cMap.get("couponName"));
					manjianList.add(cMap);
				}
			}
			
			//去除满减后的数据
			List<HashMap<String, Object>> rangeCoupList = new ArrayList<HashMap<String, Object>>();
			
			for (HashMap<String, Object> cMap : manjianList) {
				CouponRangeExample rangeExample = new CouponRangeExample();
				Integer couponId = Integer.parseInt(cMap.get("couponId").toString());
				rangeExample.createCriteria().andCouponIdEqualTo(couponId);
				List<CouponRange> rangeList = couponRangeMapper.selectByExample(rangeExample);
				//couponMap.put("couponRange", rangeList);
				String str = "";
				
				boolean flag = false;
				Integer rangId = 0;
				
				//List<HashMap<String, Object>> rulelist = (List<HashMap<String, Object>>)cMap.get("rulelist");
				for (CouponRange couponRange : rangeList) {
					if(couponRange.getRangeType() == 1){//地区
						//str = couponRange.getProvinceName()+couponRange.getCityName();
						str = PeiniUtils.cityMap.get(couponRange.getProvince().toString()).getCodesName();
						str += PeiniUtils.cityMap.get(couponRange.getCity().toString()).getCodesName();
						paramMap = new HashMap<String, Object>();
						paramMap.put("name", str);
						rulelist.add(paramMap);
						
						if(provinceId.toString().equals(couponRange.getProvince().toString()) && cityId.toString().equals(couponRange.getCity().toString())){
							flag = true;
							rangId = couponRange.getId();
						}
						
					}else if(couponRange.getRangeType() == 2){
						str = PeiniUtils.cityMap.get(couponRange.getProvince().toString()).getCodesName();
						str += PeiniUtils.cityMap.get(couponRange.getCity().toString()).getCodesName();
						str += PeiniUtils.yetaiMap.get(couponRange.getSellerType().toString()).getCodesName();
						str += PeiniUtils.yetaiMap.get(couponRange.getSellerLabel().toString()).getCodesName();
						//str = couponRange.getProvinceName()+couponRange.getCityName()+couponRange.getTypeName()+couponRange.getLabelName();
						paramMap = new HashMap<String, Object>();
						paramMap.put("name", str);
						rulelist.add(paramMap);
						
						if(provinceId.toString().equals(couponRange.getProvince().toString()) && cityId.toString().equals(couponRange.getCity().toString())
								&& sellerType.toString().equals(couponRange.getSellerType().toString()) && sellerLabel.toString().equals(couponRange.getSellerLabel().toString())
								){
							flag = true;
							rangId = couponRange.getId();
						}
						
					}else if(couponRange.getRangeType() == 3){
						//str = couponRange.getSellerName();
						SellerInfo info = sellerInfoMapper.selectByPrimaryKey(couponRange.getSellerId());
						str = info.getSellerName();
						paramMap = new HashMap<String, Object>();
						paramMap.put("name", str);
						rulelist.add(paramMap);
						
						if(sellerInfoId.toString().equals(couponRange.getSellerId())){
							flag = true;
							rangId = couponRange.getId();
						}
					}
					if(sellerInfoId.toString().equals(couponRange.getSellerId().toString())){
						flag = true;
						//logger.info(flag);
						rangId = couponRange.getId();
					}
				}
				
				if(flag == true){
					cMap.put("rangId", rangId);
					
					List<HashMap<String, Object>> rulelist = new ArrayList<HashMap<String, Object>>();
					String couponRuleText = cMap.get("couponRuleText") == null ? "" : cMap.get("couponRuleText").toString();
					if(StringUtils.isNotBlank(couponRuleText)){
						if(couponRuleText.endsWith("，")){
							couponRuleText = couponRuleText.substring(0, couponRuleText.length()-1);
						}
						String [] ss = couponRuleText.split("，");
						for (String string : ss) {
							paramMap = new HashMap<String, Object>();
							paramMap.put("name", string);
							rulelist.add(paramMap);
						}
					}
					
					cMap.put("couponRange", rulelist);
					
					String lastDate = cMap.get("lastDate").toString();
					Long vDate = DateTimeUtils.formatString2Date(lastDate, "yyyy-MM-dd").getTime();
					
					String now = DateTimeUtils.formatDateTime2String(new Date(), "yyyy-MM-dd");
					Long nDate = DateTimeUtils.formatString2Date(now, "yyyy-MM-dd").getTime();
					
					Long days = (vDate-nDate) / (24 * 60 * 60 * 1000);
					
					cMap.put("days", days);
					
					rangeCoupList.add(cMap);
				}
			}
			
			int total = rangeCoupList.size();
			if(page*rows > total){
				infoMap.put("data", rangeCoupList.subList((page-1)*rows, total));
			}else{
				infoMap.put("data", rangeCoupList.subList((page-1)*rows, page*rows));
			}
			
			infoMap.put("resultCode", Constants.SUCCESS);
			infoMap.put("resultDesc", "成功");
			
		}catch(Exception e){
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", Constants.EXCEPTION_DESC);
			logger.error(e.getMessage(),e);
		}
		//logger.info(net.sf.json.JSONObject.fromObject(infoMap));
		return infoMap;
	}*/
	
	@RequestMapping(value="/getCouponInfoByPay")
	@ResponseBody
	public Object getCouponInfoByPay(HttpServletRequest request,
			@RequestParam(value="userId") String userId,
			@RequestParam(value="sellerInfoId") Integer sellerInfoId,
			@RequestParam(value="totalMoney") Double totalMoney,
			@RequestParam(value="exclusiveMoney",required=false,defaultValue="0") Double exclusiveMoney,
			@RequestParam(value="payType") Integer payType,//1金币；2微信；3支付宝
			@RequestParam(value="page",required=false,defaultValue="1") Integer page,
			@RequestParam(value="rows",required=false,defaultValue="10") Integer rows
			){
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		try{	
			JSONObject obj = PeiniUtils.validToken(userId);
			if(obj.getInteger("resultCode") != 1){
				return obj;
			}
			userId = obj.getString("userId");
			
			BigDecimal goldNum = new BigDecimal("0");
			BigDecimal alipay = new BigDecimal("0");
			BigDecimal wxpay = new BigDecimal("0");
			int week = DateTimeUtils.getWeek();
			SellerDiscountExample sellerDiscountExample = new SellerDiscountExample();
			com.jsz.peini.bean.seller.SellerDiscountExample.Criteria sellerDiscountCriteria = sellerDiscountExample.createCriteria();
			sellerDiscountCriteria.andStartNumLessThanOrEqualTo(week);
			sellerDiscountCriteria.andEndNumGreaterThanOrEqualTo(week);
			sellerDiscountCriteria.andSellerInfoIdEqualTo(sellerInfoId);
			List<SellerDiscount> list = sellerDiscountMapper.selectByExample(sellerDiscountExample);//筛选出折扣列表
			for (SellerDiscount dis : list) {
				String frontStr = DateTimeUtils.formatDateTime2String(new Date(), "yyyy-MM-dd");
				String startTime = frontStr+" "+dis.getStartTime();
				String endTime = frontStr+" "+dis.getEndTime();
				
				Date now = new Date();//
				if((DateTimeUtils.formatString2Date(startTime, "yyyy-MM-dd HH:mm").before(now) && DateTimeUtils.formatString2Date(endTime, "yyyy-MM-dd HH:mm").after(now))
						|| startTime.equals(DateTimeUtils.formatDateTime2String(now, "yyyy-MM-dd HH:mm")) || endTime.equals(DateTimeUtils.formatDateTime2String(now, "yyyy-MM-dd HH:mm"))
						){
					goldNum = new BigDecimal(dis.getGoldNum()).divide(new BigDecimal("100"));//得到金币折扣
					alipay = new BigDecimal(dis.getZfbNum()).divide(new BigDecimal("100"));//得到支付宝折扣
					wxpay = new BigDecimal(dis.getWeixinNum()).divide(new BigDecimal("100"));//得到微信折扣
				}
			}
			
			BigDecimal payMoney = new BigDecimal("0");
			switch (payType) {
			case 1:
				if(goldNum.equals(new BigDecimal("0")) || goldNum.equals(new BigDecimal("1"))){//没有折扣
					payMoney = new BigDecimal(totalMoney);
				}else{
					BigDecimal total = new BigDecimal(totalMoney);
					BigDecimal exclusive = new BigDecimal(exclusiveMoney);
					payMoney = total.subtract(exclusive).multiply(goldNum).add(exclusive);
				}
				break;
			case 2:
				if(wxpay.equals(new BigDecimal("0")) || wxpay.equals(new BigDecimal("1"))){//没有折扣
					payMoney = new BigDecimal(totalMoney);
				}else{
					BigDecimal total = new BigDecimal(totalMoney);
					BigDecimal exclusive = new BigDecimal(exclusiveMoney);
					payMoney = total.subtract(exclusive).multiply(wxpay).add(exclusive);
				}
				break;
			case 3:
				if(alipay.equals(new BigDecimal("0")) || alipay.equals(new BigDecimal("1"))){//没有折扣
					payMoney = new BigDecimal(totalMoney);
				}else{
					BigDecimal total = new BigDecimal(totalMoney);
					BigDecimal exclusive = new BigDecimal(exclusiveMoney);
					payMoney = total.subtract(exclusive).multiply(alipay).add(exclusive);
				}
				break;
			default:
				break;
			}
			
			PageHelper.startPage(page, rows);
			HashMap<String, Object> paramMap = new HashMap<String, Object>(); 
			paramMap.put("userId", userId);
			paramMap.put("sellerId", sellerInfoId);
			paramMap.put("payMoney", payMoney.doubleValue());
			paramMap.put("payType", payType);
			paramMap.put("goldDis",totalMoney.equals(exclusiveMoney)||goldNum.equals(new BigDecimal(1))||goldNum.equals(new BigDecimal(0))?0:1);
			List<HashMap<String, Object>> cList = couponInfoMapper.getCouponInfoByPay(paramMap);
			for (HashMap<String, Object> cMap : cList) {
				List<HashMap<String, Object>> rulelist = new ArrayList<HashMap<String, Object>>();
				String couponRuleText = cMap.get("couponRuleText") == null ? "" : cMap.get("couponRuleText").toString();
				if(StringUtils.isNotBlank(couponRuleText)){
					if(couponRuleText.endsWith("，")){
						couponRuleText = couponRuleText.substring(0, couponRuleText.length()-1);
					}
					String [] ss = couponRuleText.split("，");
					for (String string : ss) {
						paramMap = new HashMap<String, Object>();
						paramMap.put("name", string);
						rulelist.add(paramMap);
					}
				}
				
				cMap.put("couponRange", rulelist);
				
				String lastDate = cMap.get("lastDate").toString();
				Long vDate = DateTimeUtils.formatString2Date(lastDate, "yyyy-MM-dd").getTime();
				
				String now = DateTimeUtils.formatDateTime2String(new Date(), "yyyy-MM-dd");
				Long nDate = DateTimeUtils.formatString2Date(now, "yyyy-MM-dd").getTime();
				
				Long days = (vDate-nDate) / (24 * 60 * 60 * 1000);
				
				cMap.put("days", days);
			}
			
			infoMap.put("data", cList);
			infoMap.put("resultCode", Constants.SUCCESS);
			infoMap.put("resultDesc", "成功");			
		}catch(Exception e){
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", Constants.EXCEPTION_DESC);
			logger.error(e.getMessage(),e);
		}
		return infoMap;
	}	
	
	/**
	 * 全部优惠券信息
	 * @param request
	 * @param couponInfo
	 * @author JGX
	 * @return
	 */
	@RequestMapping(value="/getCouponInfoByAll")
	@ResponseBody
	public Object getCouponInfoByAll(HttpServletRequest request,
			@RequestParam(value="userId") String userId,
			@RequestParam(value="type",required=false,defaultValue="0") Integer type,  //不传所有；-1过期
			@RequestParam(value="page",defaultValue="1",required=false) Integer page,
			@RequestParam(value="rows",defaultValue="10",required=false) Integer rows
			){
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		try{	
			JSONObject obj = PeiniUtils.validToken(userId);
			if(obj.getInteger("resultCode") != 1){
				return obj;
			}
			userId = obj.getString("userId");
			
			HashMap<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("userId", userId);
			if(type != null && type != 0){
				paramMap.put("type", type);
			}
			
			Page<HashMap<String, Object>> totalPage = PageHelper.startPage(page, rows);
			List<HashMap<String, Object>> cList = couponInfoMapper.getMyCouponInfo(paramMap);
			//logger.info(pg.getTotal());
			for (HashMap<String, Object> cMap : cList) {
				
				String lastDate = cMap.get("lastDate").toString();
				Long vDate = DateTimeUtils.formatString2Date(lastDate, "yyyy-MM-dd").getTime();
				
				String now = DateTimeUtils.formatDateTime2String(new Date(), "yyyy-MM-dd");
				Long nDate = DateTimeUtils.formatString2Date(now, "yyyy-MM-dd").getTime();
				
				Long days = (vDate-nDate) / (24 * 60 * 60 * 1000);
				
				cMap.put("days", days);
				
				List<HashMap<String, Object>> rulelist = new ArrayList<HashMap<String, Object>>();
				String couponRuleText = cMap.get("couponRuleText") == null ? "" : cMap.get("couponRuleText").toString();
				if(StringUtils.isNotBlank(couponRuleText)){
					if(couponRuleText.endsWith("，")){
						couponRuleText = couponRuleText.substring(0, couponRuleText.length()-1);
					}
					String [] ss = couponRuleText.split("，");
					for (int i = 0; i < ss.length; i++) {
						paramMap = new HashMap<String, Object>();
						paramMap.put("name", ss[i]);
						rulelist.add(paramMap);
					}
				}
				
				//使用规则
				/*String couponRule = cMap.get("couponRule").toString();
				List<HashMap<String, Object>> rulelist = new ArrayList<HashMap<String, Object>>();
				
				if(StringUtils.isNotBlank(couponRule)){
					String [] rules = couponRule.split(",");
					for (int i = 0; i < rules.length; i++) {
						if(StringUtils.isNotBlank(rules[i])){
							paramMap = new HashMap<String, Object>();
							
							String name = "";
							switch (rules[i]) {
								case "1":
									name = "消费满"+cMap.get("ruleMoney").toString()+"元可抵现金使用";
									break;
								case "2":
									name = "优惠范围不参与积分赠送";
									break;
								case "3":
									name = "使用优惠券不参与积分赠送";
									break;
								case "4":
									name = "优惠券与金币折扣不能同时存在";
									break;
								default:
									break;
							}
							paramMap.put("name", name);
							rulelist.add(paramMap);
						}
					}
				}
				
				CouponRangeExample rangeExample = new CouponRangeExample();
				Integer couponId = Integer.parseInt(cMap.get("couponId").toString());
				rangeExample.createCriteria().andCouponIdEqualTo(couponId);
				List<CouponRange> rangeList = couponRangeMapper.selectByExample(rangeExample);
				String str = "";*/
				/*for (CouponRange couponRange : rangeList) {
					if(couponRange.getRangeType() == 1){//地区
						str = PeiniUtils.cityMap.get(couponRange.getProvince().toString()).getCodesName();
						str += PeiniUtils.cityMap.get(couponRange.getCity().toString()).getCodesName();
						paramMap = new HashMap<String, Object>();
						paramMap.put("name", str);
						rulelist.add(paramMap);
					}else if(couponRange.getRangeType() == 2){
						str = PeiniUtils.cityMap.get(couponRange.getProvince().toString()).getCodesName();
						str += PeiniUtils.cityMap.get(couponRange.getCity().toString()).getCodesName();
						str += PeiniUtils.yetaiMap.get(couponRange.getSellerType().toString()).getCodesName();
						str += PeiniUtils.yetaiMap.get(couponRange.getSellerLabel().toString()).getCodesName();
						//str = couponRange.getProvinceName()+couponRange.getCityName()+couponRange.getTypeName()+couponRange.getLabelName();
						paramMap = new HashMap<String, Object>();
						paramMap.put("name", str);
						rulelist.add(paramMap);
					}else if(couponRange.getRangeType() == 3){
						//str = couponRange.getSellerName();
						SellerInfo info = sellerInfoMapper.selectByPrimaryKey(couponRange.getSellerId());
						str = info.getSellerName();
						paramMap = new HashMap<String, Object>();
						paramMap.put("name", str);
						rulelist.add(paramMap);
					}
				}*/
				cMap.put("couponRange", rulelist);
				String friendlyRemind = cMap.get("friendlyRemind") == null ? "" : cMap.get("friendlyRemind").toString();
				cMap.put("remindText", friendlyRemind);
			}
			
			infoMap.put("totalCnt",totalPage.getTotal());
			infoMap.put("data",cList);
			infoMap.put("resultCode", Constants.SUCCESS);
			infoMap.put("resultDesc", "成功");
		}catch(Exception e){
			infoMap.put("resultCode", Constants.FAIL);
			infoMap.put("resultDesc", "网络请求失败");
			logger.error(e.getMessage(),e);
		}
		//logger.info(net.sf.json.JSONObject.fromObject(infoMap));
		return infoMap;
	}
	
	/**
	 * 优惠券过期提醒
	 * @author Han Guohong
	 * @param request
	 * @param userId
	 * @param type
	 * @return
	 */
	@RequestMapping(value="/getCouponInfoNotify")
	@ResponseBody
	public Object getCouponInfoNotify(HttpServletRequest request,
			@RequestParam(value="userId") String userId
			){
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		try{	
			JSONObject obj = PeiniUtils.validToken(userId);
			if(obj.getInteger("resultCode") != 1){
				return obj;
			}
			userId = obj.getString("userId");
			
			//查询要过期的优惠券
			/*Date cstart = DateTimeUtils.formatString2Date(DateTimeUtils.formatDateTime2String(new Date(), "yyyy-MM-dd")+ " 00:00:00", "yyyy-MM-dd hh:mm:ss");
			Calendar now = Calendar.getInstance();
			now.set(Calendar.DATE, now.get(Calendar.DATE) + 2);
			Date cend = DateTimeUtils.formatString2Date(DateTimeUtils.formatDateTime2String(now.getTime(), "yyyy-MM-dd")+ " 00:00:00", "yyyy-MM-dd hh:mm:ss");
			HashMap<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("userId", userId);
			paramMap.put("startTime", cstart);
			paramMap.put("endTime", cend);
			List<HashMap<String, Object>> cList = couponInfoMapper.getMyCouponInfo(paramMap);
			if(cList.size() > 0){//没有不退送消息
				//查询消息表今天是否已经推送过消息
				UserSmsExample smsExample = new UserSmsExample();
				Date start = DateTimeUtils.formatString2Date(DateTimeUtils.formatDateTime2String(new Date(), "yyyy-MM-dd")+ " 00:00:00", "yyyy-MM-dd hh:mm:ss");
				Date end = DateTimeUtils.formatString2Date(DateTimeUtils.formatDateTime2String(new Date(), "yyyy-MM-dd")+ " 23:59:59", "yyyy-MM-dd hh:mm:ss");
				smsExample.createCriteria()
					.andToidEqualTo(userId)
					.andSendtimeBetween(start, end)
					.andSmstypeEqualTo(3);
				int smsCnt = userSmsMapper.countByExample(smsExample);
				if(smsCnt == 0){
					UserSms userSms = new UserSms();
					userSms.setSmsid(UUID.randomUUID().toString().replace("-", ""));
					userSms.setIsremind(1);
					userSms.setReceivdel(0);
					userSms.setSenddel(0);
					userSms.setSendtime(new Date());
					userSms.setSmscontent("您有"+cList.size()+"张优惠券即将过期！");
					userSms.setSmstype(3);
					userSms.setToid(userId);
					userSmsMapper.insertSelective(userSms);
					SmsSendUtil.sendSmsNotify(userId, null, 3, "您有"+cList.size()+"张优惠券即将过期！");
					
					//个推发送消息
					JSONObject object = new JSONObject();
			        object.put("title", "系统消息");
			        object.put("content", "您有"+cList.size()+"张优惠券即将过期！");
			        object.put("type", 3);
			        object.put("paramId", "");
			        
			        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
			        AppPush.sendPush(object,userInfo.getUserPhone().split(","));
				}
			}*/
			
			//查询今天是否需要提醒签到	
			/*boolean flag = SignRedisUtil.ifRemind(userId);
			
			if(flag == true){
				infoMap.put("isSign", false);
				SignRedisUtil.updateLastSignRemind(userId, new Date());
			}else{
				infoMap.put("isSign", true);
			}*/
			infoMap.put("isSign", true);
			
			infoMap.put("resultCode", Constants.SUCCESS);
			infoMap.put("resultDesc", "成功");
			
			RedisUtil.lpush(RedisConstants.FANS_NITIFY_THREAD, userId);
		}catch(Exception e){
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", "网络请求失败");
			logger.error(e.getMessage(),e);
		}
		return infoMap;
	}
	
	/**
	 * 获取可以用积分兑换的优惠券
	 * @author Han
	 * @param request
	 * @param userToken
	 * @param page
	 * @param rows
	 * @return
	 */
	@RequestMapping(value="/getCouponInfoList_allUnGet_byScore")
	@ResponseBody
	public Object allUnGet_byScore(HttpServletRequest request,
			@RequestParam(value="userToken",required=false) String userToken,
			@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows
			){
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		try{
			
			if(StringUtils.isNotBlank(userToken)){
				JSONObject obj = PeiniUtils.validToken(userToken);
				if(obj.getInteger("resultCode") != 1){
					return obj;
				}
				String userId = obj.getString("userId");
				
				HashMap<String, Object> uMap = new HashMap<String, Object>();
				uMap.put("userId", userId);
				List<LinkedHashMap<String, Object>> userList = userInfoMapper.getUserInfoAndLoginAccountInfo(uMap);
				if(userList.size()>0){
					HashMap<String, Object> userMap = userList.get(0);
					userMap.remove("userId");
					userMap.remove("gold");
					userMap.remove("userAccountId");
					userMap.remove("mobileNo");
					userMap.put("nickName", PeiniUtils.updateNickName(userMap.get("nickName").toString(), userMap.get("accCode").toString()));
					infoMap.put("userInfo", userMap);
				}
			}
			if(page != null && rows != null){
				Page<?> pager = PageHelper.startPage(page, rows);
			}
			List<LinkedHashMap<String,Object>> couponInfoList=couponInfoService.getCouponInfoList_allUnGet_byScore();
			infoMap.put("couponList",couponInfoList);
			infoMap.put("resultCode", Constants.SUCCESS);
			infoMap.put("resultDesc", "成功");
		}catch(Exception e){
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", "网络请求失败");
			logger.error(e.getMessage(),e);
		}
		return infoMap;
	}
	
	/**
	 * 优惠券详情
	 * @param request
	 * @param id
	 * @param getType
	 * @param userToken
	 * @return
	 */
	@RequestMapping(value="/getCouponInfo_unGet")
	@ResponseBody
	public Object detail_unGet(HttpServletRequest request,
			@RequestParam(value="id",required=true) Integer id,//优惠券id
			@RequestParam(value="getType",required=true) Integer getType,//获取方式：1活动领取；2签到领取;3积分换取；4金币购买；5消费赠送；6任务赠送；7消费最高；8任务最多；9指定id;10新用户
			@RequestParam(value="userToken",required=false) String userToken//积分兑换和金币兑换不传
			){
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		try{
			
			int isGet = 0;
			if(StringUtils.isNotBlank(userToken)){
				JSONObject obj = PeiniUtils.validToken(userToken);
				if(obj.getInteger("resultCode") != 1){
					return obj;
				}
				String userId = obj.getString("userId");
				
				HashMap<String, Object> uMap = new HashMap<String, Object>();
				uMap.put("userId", userId);
				
				//查询是否领取过了
				if(getType != null && getType == 1){
					CouponInfo couponInfo = new CouponInfo();
					couponInfo.setUserId(userId);
					couponInfo.setId(id);
					couponInfo.setGetType(getType);
					List<CouponUser> couponUserList=couponInfoService.getCouponUserByUserId(couponInfo);
					if(couponUserList.size()>0){
						isGet = 1;
					}
				}
			}
			
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("id", id);
			HashMap<String, Object> couponMap = couponInfoMapper.getCouponInfoByPrimaryKeyId(param);
			//if(getType != null && getType == 2){
				HashMap<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("couponId", id);
				paramMap.put("getType", getType);
				List<CouponGet> list = couponGetMapper.selectByCouponIdAndGetType(paramMap);
				if(list.size() > 0){
					couponMap.put("getNum", list.get(0).getGetNum());
				}else{
					couponMap.put("getNum", 0);
				}
			//}
			List<HashMap<String, Object>> rulelist = new ArrayList<HashMap<String, Object>>();
			String couponRuleText = couponMap.get("couponRuleText") == null ? "" : couponMap.get("couponRuleText").toString();
			if(StringUtils.isNotBlank(couponRuleText)){
				if(couponRuleText.endsWith("，")){
					couponRuleText = couponRuleText.substring(0, couponRuleText.length()-1);
				}
				String [] ss = couponRuleText.split("，");
				for (int i = 0; i < ss.length; i++) {
					paramMap = new HashMap<String, Object>();
					paramMap.put("name", ss[i]);
					rulelist.add(paramMap);
				}
			}
			/*String couponRule = couponMap.get("couponRule").toString();
			if(StringUtils.isNotBlank(couponRule)){
				String [] rules = couponRule.split(",");
				for (int i = 0; i < rules.length; i++) {
					if(StringUtils.isNotBlank(rules[i])){
						param = new HashMap<String, Object>();
						
						String name = "";
						switch (rules[i]) {
							case "1":
								name = "消费满"+couponMap.get("ruleMoney").toString()+"元可抵现金使用";
								break;
							case "2":
								name = "优惠范围不参与积分赠送";
								break;
							case "3":
								name = "使用优惠券不参与积分赠送";
								break;
							case "4":
								name = "优惠券与金币折扣不能同时存在";
								break;
							default:
								break;
						}
						param.put("name", name);
						rulelist.add(param);
					}
				}
			}*/
			
			/*param = new HashMap<String, Object>();
			param.put("couponId", id);
			List<CouponRange> rangeList = couponRangeMapper.selectByCouponId(param);
			//couponMap.put("couponRange", rangeList);
			String str = "";
			for (CouponRange couponRange : rangeList) {
				if(couponRange.getRangeType() == 1){//地区
					//str = couponRange.getProvinceName()+couponRange.getCityName();
					str = "仅限"+PeiniUtils.cityMap.get(couponRange.getProvince().toString()).getCodesName()+PeiniUtils.cityMap.get(couponRange.getCity().toString()).getCodesName()+"地区使用";
					param = new HashMap<String, Object>();
					param.put("name", str);
					rulelist.add(param);
				}else if(couponRange.getRangeType() == 2){
					str = "仅限"+PeiniUtils.cityMap.get(couponRange.getProvince().toString()).getCodesName()+PeiniUtils.cityMap.get(couponRange.getCity().toString()).getCodesName();
					str += PeiniUtils.yetaiMap.get(couponRange.getSellerType().toString()).getCodesName()+PeiniUtils.yetaiMap.get(couponRange.getSellerLabel().toString()).getCodesName()+"相关行业使用";
					param = new HashMap<String, Object>();
					param.put("name", str);
					rulelist.add(param);
				}else if(couponRange.getRangeType() == 3){
					str = "仅限"+couponRange.getSellerName()+"使用";
					param = new HashMap<String, Object>();
					param.put("name", str);
					rulelist.add(param);
				}
			}*/
			couponMap.put("couponRange", rulelist);
			
			infoMap.put("isGet", isGet);
			
			couponMap.put("remindText", "请在有效期内使用\n兑换后请在个人中心-代金券中查看");
			couponMap.remove("couponRule");
			
			infoMap.put("couponInfo",couponMap);
			infoMap.put("resultCode", Constants.SUCCESS);
			infoMap.put("resultDesc", "成功");
		}catch(Exception e){
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", "网络请求失败");
			logger.error(e.getMessage(),e);
		}
		logger.info(net.sf.json.JSONObject.fromObject(infoMap).toString());
		return infoMap;
	}
	
	/**
	 * 领取优惠券接口
	 * @param request
	 * @param couponInfo
	 * @author JGX
	 * @return
	 */
	@RequestMapping(value="/getCouponInfoByReceive")
	@ResponseBody
	public Object getCouponInfoByReceive(HttpServletRequest request,
			@RequestParam(value="userId") String userToken,
			@RequestParam(value="id") Integer id,//优惠券id
			@RequestParam(value="paramId",required=false) String paramId,
			@RequestParam(value="getType") Integer getType //获取方式：1活动领取；2签到领取;3积分换取；4金币购买；5消费赠送；6任务赠送；7消费最高；8任务最多；9指定id；10新用户
			){
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		try{
			JSONObject obj = PeiniUtils.validToken(userToken);
			if(obj.getInteger("resultCode") != 1){
				return obj;
			}
			String userId = obj.getString("userId");
			
			if(getType == 1 || getType == 2){
				if(StringUtils.isBlank(paramId)){
					infoMap.put("resultCode", Constants.FAIL);
					infoMap.put("resultDesc", "缺少必要参数");
					return infoMap;
				}
			}
			
			CouponInfo couponInfo =couponInfoMapper.selectByPrimaryKey(id);
			couponInfo.setUserId(userId);
			couponInfo.setId(id);
			couponInfo.setGetType(getType);
			
			List<CouponUser> couponUserList = null;
			if(getType != null && getType == 1){
				couponUserList=couponInfoService.getCouponUserByUserId(couponInfo);
				if(couponUserList.size()>0){
					infoMap.put("resultCode", Constants.FAIL);
					infoMap.put("resultDesc", "您已经领取过该优惠券，不能重复领取");
					return infoMap;
				}
			}
			
			List<CouponInfo> couponList = new ArrayList<CouponInfo>();
			CouponUser couponUser = new CouponUser();
			couponUser.setCouponId(id);
			couponUser.setCouponNum(1);
			couponUser.setGetType(getType);
			couponUser.setUserId(userId);
			couponUser.setParamId(paramId);
			
			couponList.add(couponInfo);
			infoMap = couponInfoService.rushBuyCouponResult(couponList, userId, getType,paramId);
			
			return infoMap;
		}catch(Exception e){
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", "网络请求失败");
			logger.error(e.getMessage(),e);
		}
		return infoMap;
	}
	
}
